package org.example.sys.ui.util

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager


interface Hooks {
    fun onBottom();
    fun onTop();
}

class IdleOnScrollListener(val hooks: Hooks) : RecyclerView.OnScrollListener() {

    private fun findMax(lastPositions: IntArray): Int {
        var max = lastPositions[0]
        for (value in lastPositions) {
            if (value > max) {
                max = value
            }
        }
        return max
    }

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        // 当状态为停止滑动状态时
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            recyclerView.layoutManager?.let {
                var lastPosition = 0
                var firstPosition = 0
                when (it) {
                    is GridLayoutManager -> {
                        // 通过LayoutManager找到当前显示的最后的item的position
                        lastPosition = it.findLastVisibleItemPosition()
                        firstPosition = it.findFirstVisibleItemPosition()
                    }

                    is LinearLayoutManager -> {
                        lastPosition = it.findLastVisibleItemPosition()
                        firstPosition = it.findFirstVisibleItemPosition()
                    }

                    is StaggeredGridLayoutManager -> {
                        val lastPositions = IntArray(it.getSpanCount())
                        // 得到这个数组后再取到数组中 position 值最大的那个就是最后显示的 position 值了
                        it.findLastVisibleItemPositions(
                            lastPositions
                        )
                        lastPosition = findMax(lastPositions)
                    }
                }
                if (lastPosition == it.itemCount - 1) {
                    hooks.onBottom()
                }
                if (firstPosition == 0) {
                    hooks.onBottom()
                }
            }
        }
    }
}